
<template>
    <div>
        <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"
                style="border-bottom: 1px solid #ccc" />
            <Editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml" :style="styles"
                @onCreated="handleCreated" @onChange="handleChange" @onDestroyed="handleDestroyed" @onFocus="handleFocus"
                @onBlur="handleBlur" @customAlert="customAlert" @customPaste="customPaste" />
        </div>
    </div>
</template>
  
<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { DomEditor } from '@wangeditor/editor'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

const { proxy } = getCurrentInstance();

const props = defineProps({
    /* 编辑器的内容 */
    modelValue: {
        type: String,
    },
    /* 高度 */
    height: {
        type: Number,
        default: 400,
    },
    /* 最小高度 */
    minHeight: {
        type: Number,
        default: null,
    },
    /* 只读 */
    readOnly: {
        type: Boolean,
        default: false,
    },
    /* placeholder */
    placeholder: {
        type: String,
        default: '请输入内容',
    },
});
const mode = 'default'
// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef();

const styles = computed(() => {
    let style = { overflow: 'hidden' };
    if (props.minHeight) {
        style.minHeight = `${props.minHeight}px`;
    }
    if (props.height) {
        style.height = `${props.height}px`;
    }
    return style;
})

// 内容 HTML
const valueHtml = ref("");
watch(() => props.modelValue, (v) => {
    if (v !== valueHtml.value) {
        valueHtml.value = v === undefined ? "<p></p>" : v;
    }
}, { immediate: true });


const handleDisable = (flag) => {
    const editor = editorRef.value;
    if (editor == null) return;
    if (flag) {
        editor.disable()
    } else {
        editor.enable()
    }
};

watch(() => props.disable, (v) => {
    handleDisable(v)
}, { immediate: true });


// 模拟 ajax 异步获取内容
onMounted(() => {

});

const toolbarConfig = {
    insertKeys: { // 插入的菜单
        index: 0, // 自定义
        keys: [
            'insertFormula', // “插入公式”菜单
            // 'editFormula' // “编辑公式”菜单
        ],
    },
    excludeKeys: ['group-video'] // 排除的菜单
};
const editorConfig = {
    readOnly: props.readOnly,
    placeholder: props.placeholder,
    MENU_CONF: {
        uploadImage: {
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 1024 * 1024 * 1024
        }
    },
    // 选中 公式节点 时的悬浮菜单
    hoverbarKeys: {
        formula: {
            menuKeys: ['editFormula'], // “编辑公式”菜单
        },
    },


};

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});

// 编辑器回调函数
const handleCreated = (editor) => {
    // console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！

    // nextTick(()=>{
    //     // 查看工具栏菜单
    //     const toolbar = DomEditor.getToolbar(editor);
    //     const curToolbarConfig = toolbar.getConfig();
    //     console.log(curToolbarConfig.toolbarKeys);
    // })

};
const handleChange = (editor) => {
    proxy.$emit('update:modelValue', valueHtml.value)
    // console.log('change:', editor.getHtml());
};
const handleDestroyed = (editor) => {
    // console.log('destroyed', editor);
};
const handleFocus = (editor) => {
    // console.log('focus', editor);
};
const handleBlur = (editor) => {
    // console.log('blur', editor);
};
const customAlert = (info, type) => {
    alert(`【自定义提示】${type} - ${info}`);
};
const customPaste = (editor, event, callback) => {
    // console.log('ClipboardEvent 粘贴事件对象', event);

    // 自定义插入内容
    editor.insertText('xxx');

    // 返回值（注意，vue 事件的返回值，不能用 return）
    // callback(false); // 返回 false ，阻止默认粘贴行为
    callback(true) // 返回 true ，继续默认的粘贴行为
};

</script>
  